<template>
  <!-- 用户授权二合一 -->
  <div id="dictSet">
    <Breadcrumb content="评价项目维护" />
    <div class="bodyContent">
      <Splitpanes>
        <Pane size="12">
          <!-- 字典分类  -->
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增版本" @click="addVersionDialog()"></vxe-button>
            </template>
          </vxe-toolbar>
          <el-scrollbar style="height: calc(100% - 40px)">
            <div class="sampleType">
              <el-scrollbar>
                <el-tree :expand-on-click-node="false" :default-expand-all="true" :data="versionRolseList" :props="defaultProps" node-key="id" ref="dataTreeRef" highlight-current class="tools-tree" @node-click="handleClickType" v-loading="treeloading">
                  <template #default="{ data, node }">
                    <span>{{getTreeName(data)}}</span>
                    <div>
                      <span>
                        <!-- 编辑  -->
                        <el-button v-if="data.type == '1'" type="warning" class="cirBtn" size="small" icon="Edit" circle @click="editVersionType(data, node)"></el-button>
                        <!-- 删除  -->
                        <el-button type="info" class="cirBtn" size="small" icon="Delete" circle @click="removeRoles(data)"></el-button>
                      </span>
                    </div>
                  </template>
                </el-tree>
              </el-scrollbar>
            </div>
          </el-scrollbar>
          <!-- 新建/编辑字典分类弹框 -->
          <el-dialog :title="titleClassificationType()" :show-close="false" v-model="showTypeDialog" append-to-body :close-on-click-modal="false" width="500px">
            <el-form ref="versionFormRef" :model="versionForm" :rules="dictTypeFormRule" label-width="100px" class="form-input-m" inline-message>
              <el-form-item prop="versionCode" label="编号">
                <el-input type="text" v-model="versionForm.versionCode" placeholder="请输入版本编号" clearable></el-input>
              </el-form-item>
              <el-form-item prop="versionName" label="名称">
                <el-input type="text" v-model="versionForm.versionName" placeholder="请输入版本名称" clearable></el-input>
              </el-form-item>
              <el-form-item prop="emrType" label="评测类型">
                <el-select v-model="versionForm.emrType" placeholder="请选择">
                  <el-option v-for="item in emrTypeList" :key="item.code" :label="item.name" :value="item.code" />
                </el-select>
              </el-form-item>
              <el-form-item prop="code" label="工作角色">
                <el-checkbox-group style="width: 89%" v-model="versionForm.roles">
                  <el-checkbox v-for="(item, index) in rolseList" :label="item.code" :key="index">
                    {{ item.name }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <el-form-item prop="seq" label="排序" class="input-s">
                <el-input-number v-model="versionForm.seq" :min="0" :max="100" label="请输入顺序号"></el-input-number>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer flex right justify-end">
              <el-button type="primary" @click="saveVersionType('versionFormRef')">保存</el-button>
              <el-button @click="closeTypeDialog('versionFormRef')">取消</el-button>
            </div>
          </el-dialog>
        </Pane>
        <pane size="47">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" @click="findItemList"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="handleDelete"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBox">
            <vxe-table ref="itemTableRef" border class="mytable-scrollbar"  height="auto" resizable show-header-overflow show-overflow align="left" :row-config="{ isCurrent: true, isHover: true }" @current-change="itemRowClick" :data="ItemList" >
              <vxe-column type="checkbox" width="30px" align="center"></vxe-column>
              <vxe-column field="itemCode" title="项目编号" width="100"></vxe-column>
              <vxe-column field="itemName" title="项目名称" min-width="100"></vxe-column>
              <vxe-column field="appEval" show-overflow="false" title="有效应用评价指标"></vxe-column>
              <vxe-column field="dataEval" show-overflow="false" title="数据质量评价指标"></vxe-column>
              <vxe-column field="seq" title="顺序" width="60"></vxe-column>
            </vxe-table>
          </div>
        </pane>
        <pane size="40">
          <el-tabs type="border-card" v-model="activeName" @tab-click="tabHandleClick">
            <el-tab-pane label="基本信息" name="first">
              <el-form ref="ItemFormRef" :model="emrItemForm" :rules="itemFormRule" label-width="120px" class="form-input-m baseForm" inline-message>
                <el-form-item label="项目编号" prop="itemCode">
                  <el-input type="text" v-model="emrItemForm.itemCode" placeholder="项目编号" clearable></el-input>
                </el-form-item>
                <el-form-item label="项目名称" prop="itemName">
                  <el-input type="text" v-model="emrItemForm.itemName" placeholder="项目名称" clearable></el-input>
                </el-form-item>
                <el-form-item label="有效应用评价指标" prop="appEval">
                  <el-input type="textarea" :autosize="{ minRows: 5, maxRows: 8}" v-model="emrItemForm.appEval" placeholder="有效应用评价指标" clearable></el-input>
                </el-form-item>
                <el-form-item label="数据质量评价指标" prop="dataEval">
                  <el-input type="textarea" :autosize="{ minRows: 5, maxRows: 8}" v-model="emrItemForm.dataEval" placeholder="数据质量评价指标" clearable></el-input>
                </el-form-item>
                <el-row :gutter="20">
                  <el-form-item prop="seq" label="排序" class="input-s">
                    <el-input-number v-model="emrItemForm.seq" :min="0" :max="100" label="请输入顺序号"></el-input-number>
                  </el-form-item>
                </el-row>
                <el-form-item class="form-footer">
                  <template #default>
                    <el-button type="primary" @click="clearData()">新建</el-button>
                    <el-button type="primary" @click="save('ItemFormRef')">保存</el-button>
                    <el-button type="default" @click="clearData()">重置</el-button>
                  </template>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="评价标准" name="second">
              <EmrItemStandard ref="emrStandardRef" />
            </el-tab-pane>
          </el-tabs>
        </pane>
      </Splitpanes>
    </div>
  </div>
</template>

<script lang="ts" setup>
import Breadcrumb from '@/components/Breadcrumb.vue'; //面包屑
import { Splitpanes, Pane } from 'splitpanes';
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { isEmpty } from 'lodash';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
let { proxy }: any = getCurrentInstance();
import { AppStore } from '../../stores/store';
let store = AppStore();
import EmrItemStandard from './EmrItemStandard.vue';

// 全局变量定义区 ==========
let versionRolseList: any = reactive([]); //最左侧列表数据
// 最左侧的树
let defaultProps = {
  children: 'children',
  label: 'name'
};
let sltType: any = {};
let treeloading = ref(false); //字典分类树上的刷新
let rolseList: any = reactive([]);
let emrTypeList: any = reactive([]);
let showTypeDialog = ref(false); //最左侧字典根分类弹框
// 最左侧 新建/编辑字典分类弹框表单
let versionForm = reactive({
  id: null,
  orgId: '',
  versionCode: '',
  versionName: '',
  emrType: '',
  roles: [],
  seq: 1
});
let emrItemForm = reactive({
  id: null,
  itemName: '',
  itemCode: '',
  appEval: '',
  dataEval: '',
  versionCode: '',
  roleCode: '',
  seq: 1
});
let ItemList = reactive([]);
// 弹框表单校验
let dictTypeFormRule = {
  versionName: [
    {
      required: true,
      message: '请输入版本名称',
      trigger: 'blur'
    },
    {
      min: 1,
      max: 20,
      message: '长度为1到20个字符',
      trigger: 'blur'
    }
  ],
  versionCode: [
    {
      required: true,
      message: '请输入版本编号',
      trigger: 'blur'
    },
    {
      min: 1,
      max: 20,
      message: '长度为1到20个字符',
      trigger: 'blur'
    }
  ],
  emrType: [
    {
      required: true,
      message: '请选择评测类型',
      trigger: 'blur'
    },
    {
      min: 1,
      max: 20,
      message: '长度为1到20个字符',
      trigger: 'blur'
    }
  ]
};

let itemFormRule = {
  itemName: [
    {
      required: true,
      message: '请输入项目名称',
      trigger: 'blur'
    },
    {
      min: 1,
      max: 20,
      message: '长度为1到20个字符',
      trigger: 'blur'
    }
  ],
  itemCode: [
    {
      required: true,
      message: '请输入项目名称',
      trigger: 'blur'
    },
    {
      min: 1,
      max: 20,
      message: '长度为1到20个字符',
      trigger: 'blur'
    }
  ]
};
// 方法定义区 =============
onMounted(() => {
  getRolesList();
  proxy.$nextTick(() => {
    getVersionRolesTree();
  });
});
function getTreeName(data: any) {
  if (data.type == '2') {
    return data.code + '-' + data.name;
  } else {
    return data.name+'('+data.emrTypeName+')';
  }
}
//获取病人类型数据字典
async function getRolesList() {
  rolseList.length = 0;
  emrTypeList.length = 0;
  let dictTreeTypeCodes: any = ['emrWorkRole','emrType'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const planStatues = dictTreeTypeItems.data.find((item: any) => item.code === 'emrWorkRole');
  rolseList.push(...planStatues.detailDataList);
  const inspectionStatus = dictTreeTypeItems.data.find((item) => item.code === 'emrType');
  emrTypeList.push(...inspectionStatus.detailDataList);


}

function getVersionRolesTree() {
  emrItemForm.versionCode = '';
  emrItemForm.roleCode = '';
  treeloading.value = true;
  versionRolseList.length = 0; //放入数据前清空数据
  const url = '/emr/version/getVersionRolesTree';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: {} })
    .then((res: any) => {
      versionRolseList.push(...res.data);
      if (versionRolseList.length > 0) {
        const sltObj = getChildren(versionRolseList[0]);
        sltType = sltObj;
        setCurTypeNode(sltObj.id);
        emrItemForm.versionCode = versionRolseList[0].code;
        findItemList();
      }
      treeloading.value = false;
    })
    .catch((err: any) => {
      treeloading.value = false;
      VxeMessage('获取字典分类列表失败', VxeNotifyType.error);
    });
}
// 光标定位在指定字典分类上
function setCurTypeNode(nodeId: any) {
  proxy.$nextTick(() => {
    const treeName = 'dataTreeRef';
    const tree: any = proxy.$refs[treeName];
    tree.setCurrentKey(nodeId);
  });
}
function getChildren(obj: any) {
  const children = obj.children;
  if (!isEmpty(children) && children.length > 0) {
    emrItemForm.roleCode = children[0].code;
    return getChildren(children[0]);
  } else {
    return obj;
  }
}
//点击左侧分类
function handleClickType(obj: any, node: any, data: any) {
  sltType = obj;
  ItemList.length = 0;
  clearData();
  emrItemForm.versionCode = '';
  emrItemForm.roleCode = '';
  if (obj.type == '2') {
    emrItemForm.versionCode = obj.pcode;
    emrItemForm.roleCode = obj.code;
    findItemList();
  } else {
    emrStandardRef.value.initPage(null);
  }
}

// 最左侧 新建字典根分类
function addVersionDialog() {
  if (versionRolseList.length > 0) {
    // 根分类的顺序号
    const seq = versionRolseList[versionRolseList.length - 1].seq + 1;
    versionForm.seq = seq;
  }
  showTypeDialog.value = true;
}

// 编辑小按钮
function editVersionType(item: any, node: any) {
  console.log('item', item);
  versionForm.id = item.id;
  versionForm.versionCode = item.code;
  versionForm.versionName = item.name;
  versionForm.emrType = item.emrType;
  versionForm.seq = item.seq;
  versionForm.roles = [];
  if (!isEmpty(item.children) && item.children.length > 0) {
    item.children.forEach((child: any) => {
      versionForm.roles.push(child.code);
    });
  }
  showTypeDialog.value = true;
}

// 删除字典分类小按钮
function removeRoles(row: any) {
  proxy
    .$confirm('确定删除对应版本下的角色和评价项目以及评价标准和参考样例和任务模版？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/emr/version/deleteVersionDetail';
      proxy.$http
        .post(url, row)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('删除成功', VxeNotifyType.success);
            getVersionRolesTree();
          } else {
            VxeMessage('删除失败', VxeNotifyType.error);
          }
        })
        .catch((err: any) => {
          // VxeMessage('删除字典异常', VxeNotifyType.error);
        });
    });
}
// 字典分类弹框清空校验 关闭弹框
function closeTypeDialog(formName: any) {
  const el: any = proxy.$refs[formName];
  //移除校验结果
  el.clearValidate();

  versionForm.id = null;
  versionForm.versionCode = '';
  versionForm.versionName = '';
  versionForm.emrType = '';
  versionForm.roles = [];
  versionForm.seq = 1;
  showTypeDialog.value = false;
}
// 判断弹框标题
function titleClassificationType() {
  if (versionForm.id) {
    return `编辑版本`;
  } else if (!versionForm.id) {
    return `新建版本`;
  }
}

// 字典分类 新增or保存
function saveVersionType(formName: any) {
  const el: any = proxy.$refs[formName];
  el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    // 提交前拼接 roles
    const formattedRoles = versionForm.roles.map((code: string) => {
      const role = rolseList.find((r: any) => r.code === code);
      return role ? `${role.code}-${role.name}` : code;
    });
    const obj = {
      id: versionForm.id,
      versionName: versionForm.versionName,
      versionCode: versionForm.versionCode,
      emrType: versionForm.emrType,
      roles: formattedRoles,
      seq: versionForm.seq,
      orgId: !isEmpty(versionForm.orgId) ? versionForm.orgId : store.userInfo.orgId
    };
    console.log('obj', obj);
    let url = '/emr/version/saveOrEditVersion';
    proxy.$http
      .post(url, obj)
      .then((res: any) => {
        if (res.status.code === 1) {
          if (versionForm.id) {
            VxeMessage('修改字典成功', VxeNotifyType.success);
          } else {
            VxeMessage('新增字典成功', VxeNotifyType.success);
          }
          getVersionRolesTree();
          showTypeDialog.value = false;
          // 清空表单
          // clearDictTypeForm();
        } else {
          if (versionForm.id) {
            VxeMessage('修改字典失败', VxeNotifyType.error);
          } else {
            VxeMessage('新增字典失败', VxeNotifyType.error);
          }
        }
      })
      .catch((err: any) => {
        VxeMessage('保存异常', VxeNotifyType.error);
      });
  });
}
let activeName = ref('first');
let emrStandardRef: any = ref(null);
function tabHandleClick(tab) {
  if (tab.props.name == 'second') {
    emrStandardRef.value.initPage(emrItemForm);
  }
}

// 新建&重置
function clearData() {
  emrItemForm.id = null;
  emrItemForm.itemCode = '';
  emrItemForm.itemName = '';
  emrItemForm.appEval = '';
  emrItemForm.dataEval = '';
  emrItemForm.seq = ItemList.length + 1;
}
// 保存
function save(formName: any) {
  const el: any = proxy.$refs[formName];
  el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    if (isEmpty(emrItemForm.versionCode) || isEmpty(emrItemForm.roleCode)) {
      VxeMessage('请选择版本和角色', VxeNotifyType.error);
      return;
    }
    let url = '';
    url = '/emr/item/addOrUpdateEmrItem';
    proxy.$http
      .post(url, emrItemForm)
      .then((res: any) => {
        VxeMessage(res.status.msg, VxeNotifyType.success);
        findItemList();
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
  });
}

// 中间获取当前字典的字段列表(默认获得全部)
function findItemList() {
  clearData();
  ItemList.length = 0; //放入数据前清空数据
  const url = '/emr/item/findEmrItemList';
  proxy.$http
    //注意此处的数据条数
    .post(url, emrItemForm)
    .then((res: any) => {
      ItemList.push(...res.data);
      //if (ItemList.length > 0) {
      itemRowClick({ row: ItemList[0] }); //默认选中第一条数据
      //}
    })
    .catch((err: any) => {
      // VxeMessage('获取获取当前字典的字段列表失败',VxeNotifyType.error)
    });
}

// 点击字段当前行触发的事件
function itemRowClick({ row }: any) {
  if (isEmpty(row)) {
    Object.assign(emrItemForm, {});
    emrStandardRef.value.initPage(row);
  } else {
    Object.assign(emrItemForm, row);
    (proxy.$refs.itemTableRef as any).setCurrentRow(row);
  }
  //TODO 查询细项
  if (activeName.value == 'second') {
    emrStandardRef.value.initPage(emrItemForm);
  }
}

function handleDelete() {
  proxy
    .$confirm('确定删除评价项目以及评价标准和参考样例和任务模版？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const selectRows = (proxy.$refs.itemTableRef as any).getCheckboxRecords();
      if (selectRows.length == 0) {
        VxeMessage('请选择需要删除的项目', VxeNotifyType.warning);
        return;
      }
      const url = '/emr/item/deleteEmrItemList';
      proxy.$http
        .post(url, selectRows)
        .then((res: any) => {
          findItemList();
          VxeMessage(res.status.msg, VxeNotifyType.success);
        })
        .catch((err: any) => {
          VxeMessage(err, VxeNotifyType.error);
        });
    });
}
</script>

<style lang="scss" scoped>
#dictSet {
  width: 100%;
  height: 100%;
  .bodyContent {
    // 面包屑40px  上下间距10px
    height: calc(100% - 60px);

    .splitpanes {
      background-color: $base-white;
      height: 100%;

      :deep(.el-tabs) {
        height: 100%;
        .el-tabs__content {
          height: calc(100% );
          padding: 0;
          .el-tab-pane {
            height: 90%;
          }
        }
      }

      // 附加按钮间距
      .button-blue {
        margin: 5px 0 5px 5px;
      }
      .button-red {
        margin: 5px 0 5px 5px;
      }
      // 最左侧字典分类的树
      .sampleType {
        .tools-tree {
          min-width: 168px;
          padding: 0 5px 5px 5px;
          font-size: $font-size;
          border: none;
          .cirBtn {
            display: none;
            width: 16px;
            height: 16px;
            padding: 0px;
            margin-left: 10px;
          }
          .el-tree-node__content:hover {
            .cirBtn {
              display: inline-block !important;
            }
          }
        }
      }

      // 中间
      .tableBox {
        width: 100%;
        height: calc(100% - 40px);
      }
    }
  }
}
</style>
